package com.service.impl;
import com.service.DrawingBedService;
import org.springframework.stereotype.Service;

import java.io.*;
import java.net.HttpURLConnection;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
@Service
public class DrawingBedServiceImpl implements DrawingBedService {

    @Override
    public String drawBed(String src) throws IOException {
        String url = "http://127.0.0.1:36677/upload";
        String json =
                "{\n" +
                        "\t\"list\":[\n" +
                        "\t\t\"" +
                        src +
                        "\"\n" +
                        "\t]\n" +
                        "}"; // 请求体必须是JSON格式
        HttpURLConnection conn = (HttpURLConnection) new URL(url).openConnection();
        conn.setRequestMethod("POST"); // 设置请求方法为POST
        conn.setDoOutput(true); // 设置是否允许输出
        conn.setRequestProperty("Content-Type", "application/json; utf-8"); // 设置请求头的Content-Type
        // 写入请求体
        try (OutputStream os = conn.getOutputStream()) {
            byte[] input = json.getBytes(StandardCharsets.UTF_8);
            os.write(input, 0, input.length);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        // 获取响应状态码
        int responseCode = conn.getResponseCode();
        System.out.println("Response Code : " + responseCode);
        // 根据响应状态码选择输入流
        InputStream inputStream;
        if (responseCode == HttpURLConnection.HTTP_OK) { // 成功响应
            inputStream = conn.getInputStream();
        } else { // 错误响应
            inputStream = conn.getErrorStream();
        }
        // 读取并打印响应内容
        try (BufferedReader in = new BufferedReader(new InputStreamReader(inputStream))) {
            String inputLine;
            StringBuffer response = new StringBuffer();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            System.out.println("Response: " + response.toString());
            Pattern pattern = Pattern.compile("http[s]?://[^']*?\"");
            Matcher matcher = pattern.matcher(response);
            String return_url = null;
            while (matcher.find()) {
                return_url = matcher.group();
                //System.out.println(return_url);
            }
            return_url = return_url.substring(0, return_url.length() - 1);
            System.out.println(return_url);
            return return_url;
        }catch (IOException e){
            return null;
        }

    }
}
